import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './index.less';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Popconfirm } from 'antd';
import { IconC, SelectC, InputNumberC } from '../../../comps';
import dictData from './config';
import AddFenzi from './addFenzi';
import _ from 'lodash';

@Form.create()
class AssetIndexC extends PureComponent {
  state = {
    visible: false, //分子分母是否可见
    indexItem: undefined, //分子分母的详情数据
    indexType: undefined, //类型 是新增分子还是分母
    warnList: [],
    addType: undefined, //1新增 2编辑
  };

  componentDidMount() {
    this.props.onRef(this);
    this.formatwarnList(); //触警操作列表
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  //编辑分子分母
  editfzfm = (obj, type) => {
    this.setState({
      indexType: type,
    });
    if (!obj) {
      //新增
      this.setState({
        visible: true,
        addType: 1,
      });
    } else {
      //编辑
      this.setState({
        visible: true,
        indexItem: _.cloneDeep(obj),
        addType: 2,
      });
    }
  };
  //点击删除  前端删除 保存之后给后端 才能生效
  onDeleteItem = (id) => {
    // this.props.deleteFenzi(id)
    const indexList = this.props.detailData?.indexList || [];
    const arr = indexList.filter((item) => item.indexId != id);
    this.props.changeDetailData(arr); //通知父级修改indexlist
  };

  fenziRender = (data, type) => {
    return (
      <div className={myStyle.fenziWrapper}>
        <div className={myStyle.fenziItem}>
          {data.length ? (
            <div className={myStyle.fenzihasData}>
              {data.map((item, index) => {
                return (
                  <div key={index}>
                    {index == 0 && item.operateMode == 2 ? <div>0</div> : null}
                    <div className={myStyle.fuhaoItem}>{item.operateMode == 1 ? (index == 0 ? '' : '+') : '-'}</div>
                    <div className={myStyle.indexName} title={item.indexName}>
                      {item.indexName}
                    </div>
                    <div className={myStyle.fenzioprate}>
                      <IconC
                        isHover={false} //鼠标悬停是否更换图标
                        type={'edit'}
                        title='编辑'
                        onClick={(e) => {
                          this.editfzfm(item, type);
                        }}
                      />

                      <Popconfirm
                        title={'确定删除？'}
                        icon={<ExclamationCircleOutlined />}
                        onConfirm={() => {
                          this.onDeleteItem(item.indexId);
                        }}
                      >
                        <IconC
                          isHover={false} //鼠标悬停是否更换图标
                          type={'delete'}
                          title='删除'
                        />
                      </Popconfirm>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className={myStyle.noData}>
              <span>{type == '1' ? '请输入分子' : '请输入分母'}</span>
            </div>
          )}
        </div>
        <div className={myStyle.addFenzi}>
          <IconC
            style={{ width: '14px', height: '14px' }}
            isHover={false} //鼠标悬停是否更换图标
            type={'newly'}
            title='新增'
            onClick={() => this.editfzfm(undefined, type)}
          />
        </div>
      </div>
    );
  };
  //分子点击取消
  onCancel = () => {
    this.setState({
      visible: false,
      indexItem: undefined,
    });
  };
  //分子点击确定
  onOK = (row) => {
    const indexList = this.props.detailData?.indexList || [];
    const arr = _.cloneDeep(indexList);
    if (this.state.addType == 2) {
      //编辑
      for (let index = 0; index < indexList.length; index++) {
        const item = indexList[index];
        if (item.indexId === row.indexId) {
          arr.splice(index, 1, row); //替换修改的那个分子
        }
      }
      this.props.changeDetailData(arr); //通知列表页的组件里详情record修改
    } else {
      //新增
      indexList.push(row);
      this.props.changeDetailData(indexList); //通知列表页的组件里详情record修改
    }
    this.setState({
      visible: false,
      indexItem: undefined,
    });
  };
  //触警操作列表 调整格式进行展示
  formatwarnList = () => {
    const { detailData } = this.props;
    const arr = [];
    if (JSON.stringify(detailData) != '{}') {
      if (detailData.valveValue1 !== null) {
        arr.push({
          valveValue1: detailData.valveValue1,
          valveType1: detailData.valveType1,
          keys: ['valveValue1', 'valveType1'],
        });
      }
      if (detailData.valveValue2 !== null) {
        arr.push({
          valveValue2: detailData.valveValue2,
          valveType2: detailData.valveType2,
          keys: ['valveValue2', 'valveType2'],
        });
      }
      if (detailData.valveValue3 !== null) {
        arr.push({
          valveValue3: detailData.valveValue3,
          valveType3: detailData.valveType3,
          keys: ['valveValue3', 'valveType3'],
        });
      }
    } else {
      arr.push({ keys: ['valveValue1', 'valveType1'] });
    }
    this.setState({ warnList: [...arr] });
  };
  //删除触警
  delWarn = (data) => {
    const { warnList } = this.state;
    const arr = warnList.filter((item) => {
      return JSON.stringify(data.keys) != JSON.stringify(item.keys);
    });
    this.setState({ warnList: [...arr] });
  };
  //新增触警
  addWarn = () => {
    const { warnList } = this.state;
    warnList.push({ keys: ['valveValue2', 'valveType2'] });
    this.setState({ warnList: [...warnList] });
  };
  //提交代码
  submit = () => {
    const {
      form: { validateFields },
      detailData = {},
    } = this.props;
    var query = undefined;
    validateFields((err, values) => {
      console.log('资产指标', values);
      if (!err) {
        if (values.shiftValue == null || values.shiftValue == undefined) {
          message.error('数值必填');
          return;
        }
        if (values.valveType1 == values.valveType2) {
          message.error('触警操作不可重复');
          return;
        }
        if (!detailData.indexList) {
          message.error('分子必须填写');
          return;
        } else {
          const fenziList = detailData.indexList.filter((item) => item.ctrlType == 1); //分子1
          // const fenmuList = detailData.indexList.filter(item => item.ctrlType == 2);//分母2
          if (!fenziList.length) {
            message.error('分子必须填写');
            return;
          }
        }
        query = {
          ...values,
          indexList: detailData.indexList || [],
        };
      }
    });
    return query;
  };
  render() {
    const { detailData = {} } = this.props;
    const { warnList } = this.state;
    const indexList = detailData.indexList || [];
    const fenziList = indexList.filter((item) => item.ctrlType == 1); //分子1
    const fenmuList = indexList.filter((item) => item.ctrlType == 2); //分母2

    return (
      <div>
        <Row>
          <Col span={6}>
            <SelectC
              form={this.props.form}
              dataIndex='singleTargetControl'
              title='资产控制方式'
              initialValue={detailData.singleTargetControl === true ? '1' : '2'}
              dataSource={dictData.singleTargetControl}
              rules={[{ required: true, message: '请选择资产控制方式' }]}
            />
          </Col>
          <Col span={6}>
            <SelectC
              form={this.props.form}
              dataIndex='absControlFlag'
              title='绝对值控制'
              initialValue={detailData.absControlFlag || '2'}
              dataSource={dictData.falseOrTrue}
              rules={[{ required: true, message: '请选择绝对值控制' }]}
            />
          </Col>
          <Col span={6}>
            <SelectC
              form={this.props.form}
              dataIndex='pecent'
              title='展示格式'
              initialValue={detailData.pecent == null || detailData.pecent == undefined ? '1' : detailData.pecent == true ? '1' : '2'}
              dataSource={dictData.pecent}
            />
          </Col>
        </Row>
        <div className={myStyle.formula}>
          <span>计算公式:</span>
          <div>
            <div className={myStyle.leftItem}>
              <div className={myStyle.title}>公式</div>
              <div className={myStyle.gongshi}>
                <div>
                  <div className={myStyle.shuzhi}>
                    <InputNumberC form={this.props.form} dataIndex={'shiftValue'} initialValue={detailData.shiftValue || 0} precision={4} placeholder={'请填写数值'} />
                  </div>
                  <div className={myStyle.fuhao}>
                    <SelectC
                      form={this.props.form}
                      dataIndex={'shiftMethod'}
                      initialValue={detailData.shiftMethod ? detailData.shiftMethod.toString() : '1'}
                      dataSource={dictData.shiftMethod}
                    />
                  </div>
                  <div className={myStyle.fenzi}>
                    {this.fenziRender(fenziList, '1')}
                    {this.fenziRender(fenmuList, '2')}
                  </div>
                </div>
              </div>
            </div>
            <div className={myStyle.centerItem}>
              <div className={myStyle.title}>比较方向</div>
              <div>
                <SelectC
                  form={this.props.form}
                  dataIndex={'compareMethod'}
                  initialValue={detailData.compareMethod ? detailData.compareMethod.toString() : '1'}
                  dataSource={dictData.directionList}
                  rules={[{ required: true, message: '必填' }]}
                />
              </div>
            </div>
            <div className={myStyle.rightItem}>
              <div className={myStyle.rightItemTitle}>
                <div>
                  <span>控制值</span>
                  <span>触警操作</span>
                </div>
              </div>
              <div className={myStyle.oprate}>
                {warnList.map((item, key) => {
                  return (
                    <div key={key}>
                      <div>
                        <InputNumberC
                          form={this.props.form}
                          dataIndex={item.keys[0]}
                          precision={4}
                          initialValue={detailData[item.keys[0]]}
                          rules={[{ required: true, message: '请填写控制值' }]}
                        />
                      </div>
                      <div>
                        <SelectC
                          form={this.props.form}
                          dataIndex={item.keys[1]}
                          initialValue={detailData[item.keys[1]]}
                          dataSource={dictData.warnList}
                          rules={[{ required: true, message: '请选择触警操作' }]}
                        />
                      </div>
                      {key != 0 && (
                        <span className={myStyle.delBtn}>
                          <IconC
                            isHover={false} //鼠标悬停是否更换图标
                            type={'delete'}
                            title='删除'
                            onClick={(e) => {
                              this.delWarn(item);
                            }}
                          />
                        </span>
                      )}
                    </div>
                  );
                })}
              </div>
              {warnList.length < dictData.warnList.length && (
                <div className={myStyle.addBtn}>
                  <IconC
                    isHover={false} //鼠标悬停是否更换图标
                    type={'newly'}
                    title='新增'
                    onClick={this.addWarn}
                  />
                </div>
              )}
            </div>
          </div>
        </div>
        {this.state.visible && (
          <AddFenzi onCancel={this.onCancel} onOK={this.onOK} visible={this.state.visible} indexType={this.state.indexType} detailData={this.state.indexItem} />
        )}
      </div>
    );
  }
}
export default connect(({ limitManagemen, dictionaryM, userM: user, loading }) => ({
  limitManagemen,
  dictionaryM,
  user,
  loading,
}))(AssetIndexC);
